Skip to content

使用 Spring Data Redis 监听 Redis 中的 Key 过期事件

配置 Spring Data Redis

kotlin
import com.linkershow.adplan.redis.KeyExpiredListener
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.listener.RedisMessageListenerContainer



@Configuration
class RedisConfig {

    @Autowired
    private lateinit var redisTemplate: StringRedisTemplate

    @Bean
    fun redisMessageListenerContainer(): RedisMessageListenerContainer {
        val redisMessageListenerContainer = RedisMessageListenerContainer()
        redisMessageListenerContainer.setConnectionFactory(redisTemplate.connectionFactory!!)
        return redisMessageListenerContainer
    }

    @Bean
    fun keyExpiredListener(): KeyExpiredListener {
        return KeyExpiredListener(this.redisMessageListenerContainer())
    }

}

编写 Redis 中的 Key 过期事件监听类

kotlin
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.connection.Message
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import java.nio.charset.StandardCharsets

class KeyExpiredListener(listenerContainer: RedisMessageListenerContainer) : KeyExpirationEventMessageListener(listenerContainer) {

    @Autowired
    private lateinit var adPlanGenerateService: AdPlanGenerateService

    override fun onMessage(message: Message, pattern: ByteArray?) {

        val key = String(message.body, StandardCharsets.UTF_8)

        println("Deleted key is ...${key}")
    }

}

Released under the MIT License.